package com.example.socialapp.ui.theme

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

/**
 * 主题自定义数据类，包含所有主题设置
 */
data class ThemeSettings(
    val isDarkMode: Boolean,
    val useSystemDarkMode: Boolean,
    val useDynamicTheme: Boolean,
    val colorScheme: ColorScheme,
    val fontScale: FontScale
)

/**
 * 主题自定义屏幕
 * 
 * @param onNavigateBack 返回上一个屏幕的回调
 * @param onApplyTheme 应用主题设置的回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ThemeCustomizationScreen(
    onNavigateBack: () -> Unit,
    onApplyTheme: (ThemeSettings) -> Unit
) {
    val scrollState = rememberScrollState()
    
    // 主题模式状态
    var isDarkMode by remember { mutableStateOf(false) }
    
    // 主题颜色状态
    var selectedColorScheme by remember { mutableStateOf(ColorScheme.PURPLE) }
    
    // 是否使用系统深色模式状态
    var useSystemDarkMode by remember { mutableStateOf(true) }
    
    // 是否使用动态主题状态 (Android 12+ Material You)
    var useDynamicTheme by remember { mutableStateOf(true) }
    
    // 字体缩放状态
    var fontScale by remember { mutableStateOf(FontScale.MEDIUM) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { 
                    Text(
                        text = "主题设置",
                        style = MaterialTheme.typography.titleLarge
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = {
                        val settings = ThemeSettings(
                            isDarkMode = isDarkMode,
                            useSystemDarkMode = useSystemDarkMode,
                            useDynamicTheme = useDynamicTheme,
                            colorScheme = selectedColorScheme,
                            fontScale = fontScale
                        )
                        onApplyTheme(settings)
                    }) {
                        Icon(
                            imageVector = Icons.Default.Save,
                            contentDescription = "应用主题"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    val settings = ThemeSettings(
                        isDarkMode = isDarkMode,
                        useSystemDarkMode = useSystemDarkMode,
                        useDynamicTheme = useDynamicTheme,
                        colorScheme = selectedColorScheme,
                        fontScale = fontScale
                    )
                    onApplyTheme(settings)
                }
            ) {
                Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "应用主题"
                )
            }
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(scrollState)
        ) {
            // 显示模式设置
            SettingSection(title = "显示模式") {
                SettingItem(
                    title = "跟随系统",
                    subtitle = "根据系统深色/浅色模式自动切换",
                    trailingContent = {
                        Switch(
                            checked = useSystemDarkMode,
                            onCheckedChange = { 
                                useSystemDarkMode = it 
                                if (it) {
                                    // 如果启用系统跟随，则禁用手动深色模式设置
                                    isDarkMode = false
                                }
                            }
                        )
                    }
                )
                
                if (!useSystemDarkMode) {
                    SettingItem(
                        title = "深色模式",
                        subtitle = "手动设置深色/浅色模式",
                        trailingContent = {
                            Switch(
                                checked = isDarkMode,
                                onCheckedChange = { isDarkMode = it }
                            )
                        }
                    )
                }
            }
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 主题颜色设置
            SettingSection(title = "主题颜色") {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    ColorScheme.values().forEach { colorScheme ->
                        ColorSchemeItem(
                            colorScheme = colorScheme,
                            isSelected = selectedColorScheme == colorScheme,
                            onClick = { selectedColorScheme = colorScheme }
                        )
                    }
                }
            }
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 动态主题设置
            SettingSection(title = "动态主题") {
                SettingItem(
                    title = "Material You",
                    subtitle = "使用您壁纸的颜色创建个性化主题 (需要 Android 12+)",
                    trailingContent = {
                        Switch(
                            checked = useDynamicTheme,
                            onCheckedChange = { useDynamicTheme = it }
                        )
                    }
                )
            }
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 字体大小设置
            SettingSection(title = "字体大小") {
                FontScale.values().forEach { scale ->
                    SettingItem(
                        title = scale.displayName,
                        subtitle = "将文字大小调整为${scale.displayName}",
                        trailingContent = {
                            RadioButton(
                                selected = fontScale == scale,
                                onClick = { fontScale = scale }
                            )
                        }
                    )
                }
            }
            
            // 主题预览
            ThemePreview(
                isDarkMode = isDarkMode,
                colorScheme = selectedColorScheme
            )
            
            // 应用按钮
            Button(
                onClick = {
                    val settings = ThemeSettings(
                        isDarkMode = isDarkMode,
                        useSystemDarkMode = useSystemDarkMode,
                        useDynamicTheme = useDynamicTheme,
                        colorScheme = selectedColorScheme,
                        fontScale = fontScale
                    )
                    onApplyTheme(settings)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 24.dp)
            ) {
                Text("应用主题设置", modifier = Modifier.padding(vertical = 8.dp))
            }
            
            Spacer(modifier = Modifier.height(24.dp))
        }
    }
}

/**
 * 设置区块
 */
@Composable
private fun SettingSection(
    title: String,
    content: @Composable () -> Unit
) {
    Column {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(start = 16.dp, top = 16.dp, bottom = 8.dp)
        )
        content()
    }
}

/**
 * 设置项
 */
@Composable
private fun SettingItem(
    title: String,
    subtitle: String? = null,
    trailingContent: @Composable () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleSmall
            )
            if (subtitle != null) {
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
        
        trailingContent()
    }
}

/**
 * 颜色方案项
 */
@Composable
private fun ColorSchemeItem(
    colorScheme: ColorScheme,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .size(48.dp)
            .clip(CircleShape)
            .background(colorScheme.primaryColor)
            .border(
                width = if (isSelected) 3.dp else 1.dp,
                color = if (isSelected) MaterialTheme.colorScheme.onBackground else Color.Transparent,
                shape = CircleShape
            )
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        if (isSelected) {
            Icon(
                imageVector = Icons.Default.Check,
                contentDescription = "已选择",
                tint = colorScheme.onPrimaryColor
            )
        }
    }
}

/**
 * 主题预览卡片
 */
@Composable
private fun ThemePreview(
    isDarkMode: Boolean,
    colorScheme: ColorScheme
) {
    val backgroundColor = if (isDarkMode) Color.Black.copy(alpha = 0.8f) else Color.White
    val textColor = if (isDarkMode) Color.White else Color.Black
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = backgroundColor
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "主题预览",
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp,
                color = textColor,
                modifier = Modifier.padding(bottom = 16.dp),
                textAlign = TextAlign.Center
            )
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                PreviewElement(
                    color = colorScheme.primaryColor,
                    name = "Primary",
                    textColor = colorScheme.onPrimaryColor
                )
                
                PreviewElement(
                    color = colorScheme.secondaryColor,
                    name = "Secondary",
                    textColor = colorScheme.onSecondaryColor
                )
                
                PreviewElement(
                    color = colorScheme.tertiaryColor,
                    name = "Tertiary",
                    textColor = colorScheme.onTertiaryColor
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            Text(
                text = "这是一个示例文本，展示当前主题的外观。",
                color = textColor,
                textAlign = TextAlign.Center
            )
        }
    }
}

/**
 * 主题预览元素
 */
@Composable
private fun PreviewElement(
    color: Color,
    name: String,
    textColor: Color
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(color),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "A",
                color = textColor,
                fontWeight = FontWeight.Bold
            )
        }
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = name,
            fontSize = 12.sp,
            color = MaterialTheme.colorScheme.onBackground
        )
    }
}

/**
 * 颜色方案枚举
 */
enum class ColorScheme(
    val displayName: String,
    val primaryColor: Color,
    val onPrimaryColor: Color,
    val secondaryColor: Color,
    val onSecondaryColor: Color,
    val tertiaryColor: Color,
    val onTertiaryColor: Color
) {
    PURPLE(
        displayName = "紫色",
        primaryColor = Color(0xFF6750A4),
        onPrimaryColor = Color.White,
        secondaryColor = Color(0xFF625B71),
        onSecondaryColor = Color.White,
        tertiaryColor = Color(0xFF7D5260),
        onTertiaryColor = Color.White
    ),
    BLUE(
        displayName = "蓝色",
        primaryColor = Color(0xFF0061A4),
        onPrimaryColor = Color.White,
        secondaryColor = Color(0xFF535F70),
        onSecondaryColor = Color.White,
        tertiaryColor = Color(0xFF6B5778),
        onTertiaryColor = Color.White
    ),
    GREEN(
        displayName = "绿色",
        primaryColor = Color(0xFF006E1C),
        onPrimaryColor = Color.White,
        secondaryColor = Color(0xFF4D6356),
        onSecondaryColor = Color.White,
        tertiaryColor = Color(0xFF3A656F),
        onTertiaryColor = Color.White
    ),
    ORANGE(
        displayName = "橙色",
        primaryColor = Color(0xFFB64D00),
        onPrimaryColor = Color.White,
        secondaryColor = Color(0xFF76574A),
        onSecondaryColor = Color.White,
        tertiaryColor = Color(0xFF665B21),
        onTertiaryColor = Color.White
    ),
    RED(
        displayName = "红色",
        primaryColor = Color(0xFFBE0030),
        onPrimaryColor = Color.White,
        secondaryColor = Color(0xFF775657),
        onSecondaryColor = Color.White,
        tertiaryColor = Color(0xFF744C79),
        onTertiaryColor = Color.White
    )
}

/**
 * 字体大小枚举
 */
enum class FontScale(val displayName: String, val scale: Float) {
    SMALL("小号", 0.85f),
    MEDIUM("中号", 1.0f),
    LARGE("大号", 1.15f),
    EXTRA_LARGE("特大号", 1.3f)
} 